package com.stylefeng.guns.modular.system.controller;

import cn.hutool.core.date.DateTime;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.Tip;
import com.stylefeng.guns.core.cache.CacheKit;
import com.stylefeng.guns.core.common.Tools.Result;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.Duty;
import com.stylefeng.guns.modular.system.service.IDutyService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 职务表控制器
 *
 * @author fengshuonan
 * @Date 2018-09-04 17:58:47
 */
@Controller
@RequestMapping(value = {"/gunsApi/auth/duty"})
public class DutyController extends BaseController {

    private String PREFIX = "/system/duty/";

    @Autowired
    private IDutyService dutyService;

    /**
     * 跳转到职务表首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "duty.html";
    }

    /**
     * 跳转到添加职务表
     */
    @RequestMapping("/duty_add")
    public String dutyAdd() {
        return PREFIX + "duty_add.html";
    }

    /**
     * 跳转到修改职务表
     */
    @RequestMapping("/duty_update/{dutyId}")
    public String dutyUpdate(@PathVariable Integer dutyId, Model model) {
        Duty duty = dutyService.selectById(dutyId);
        model.addAttribute("item", duty);
        LogObjectHolder.me().set(duty);
        return PREFIX + "duty_edit.html";
    }

    /**
     * 获取职务表列表
     */
    @BussinessLog(value = "添加职务")
    @GetMapping(value = "/list")
    @ResponseBody
    public Result list(@ApiParam(name = "condition", value = "职务名称", type = "String", required = false) @RequestParam(value = "condition", required = false) String condition) {
        Map map = new HashMap();
        map.put("sd_name", condition);
        return Result.success(this.dutyService.selectByMap(map));
    }

    /**
     * 新增职务表
     */
    @PostMapping(value = "/add", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Tip add(@Valid @RequestBody @ApiParam(name = "org", value = "添加新职务", required = true) Duty duty, BindingResult result) {
        if (result.hasErrors()) {
            throw new GunsException(BizExceptionEnum.REQUEST_NULL);
        }

        if (ToolUtil.isOneEmpty(duty, duty.getSdName())) {
            throw new GunsException(BizExceptionEnum.REQUEST_NULL);
        }
        //完善pids,根据pid拿到pid的pids
        ShiroUser shiroUser = this.getShiroUser();
        if (shiroUser != null) {
            duty.setCreateUser(shiroUser.getName());
            duty.setCreateTime(new Date());
        }
        dutyService.insert(duty);
        return SUCCESS_TIP;
    }

    /**
     * 删除职务表
     */
    @RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    @ResponseBody
    public Tip delete(@ApiParam(value = "职务ID", name = "dutyId") @RequestParam(value = "dutyId") Integer dutyId) {
        Duty duty = this.dutyService.selectById(dutyId);
        if (duty == null) {
            return new ErrorTip(BizExceptionEnum.DUTY_NOT_EXISTS.getCode(), BizExceptionEnum.DUTY_NOT_EXISTS.getMessage());
        }
        boolean f = dutyService.deleteById(dutyId);
        if (f)
            return SUCCESS_TIP;
        else
            return new ErrorTip(402, "删除失败");
    }

    /**
     * 修改职务表
     */
    @PostMapping(value = "/update")
    @ResponseBody
    public Tip update(@ApiParam(name = "duty", value = "职务对象", required = true) @RequestBody Duty duty) {
        ShiroUser shiroUser = this.getShiroUser();
        if (shiroUser != null) {
            duty.setUpdateUser(shiroUser.getName());
            duty.setUpdateTime(DateTime.now());
        }
        Boolean f =  dutyService.updateById(duty);
        if (f)
            return SUCCESS_TIP;
        else
            return new ErrorTip(401, "更新失败");
 }

    /**
     * 职务表详情
     */
    @RequestMapping(value = "/detail")
    @ResponseBody
    public Result detail(@ApiParam(name = "dutyId", value = "职务ID", required = true)  @RequestParam("dutyId") Integer dutyId) {
        return Result.success(dutyService.selectById(dutyId));
    }

    @Cacheable(value="local",key = "'userCw_'+#result.getId()")
    public  ShiroUser getShiroUser(){
        String token= getHttpServletRequest().getHeader("Authorization").substring(7);
        return CacheKit.get(CACHE_STRATEGY,token);
    }
}
